<?php

class ExpUserfunc extends ExpFunction
{
	private $name;

	public function __construct ($name)
	{
		$this->name = $name;
	}

	public function call (ArgContext $args)
	{
		$proto = $args->getContext()->getUserfunc($this->name);

		$acount = count($args);
		$pcount = count($proto['args']);

		// Argument count must match
		if ($acount !== $pcount)
		{
			throw new CliUserFunctionException(
				"{$this->name}: Expected '$acount' arguments, got '$pcount'");
		}

		// Create new subcontext to avoid overwriting global variables
		$subcont = $context->createChild();

		// Assign values to all the argument variables in the function
		foreach ($proto['args'] as $key => $varname)
		{
			$var = new ExpVariable($varname);
			$var->set($args[$key], $subcont);
		}

		return $proto['func']->getValue($subcont) . '(';

	}
}